layui.define(['jquery', 'element','laytpl','form','upload'], function(exports) {
	"use strict";

	/**
	 * 常用封装类
	 * */
	var MOD_NAME = 'exam',
		$ = layui.jquery,
		element = layui.element,
        form = layui.form,
        laytpl = layui.laytpl,
        upload = layui.upload;
	var exam = new function() {
        this.options ={
            data:null,
            url:'',
            type:'',
            targetlayer:null,
            varifylayer:null,
            workerlayer:null
        } ;
        /**
         * 模板布局
         */
        this.tplrender = function (data, dom) {
            let _this = this;
            var templateInst = laytpl(`
                <form class="common-title  layui-form" action="">
                    <div class="common-menu">
                        <div class="menu menu1">
                            <button type="submit" class="pear-btn pear-btn-warming" lay-submit lay-filter="submitSave">提交答案</button>
                        </div>
                        <div class="menu menu2 layui-hide">
                            <button class="pear-btn pear-btn-warming">下一题</button>
                        </div>
                    </div>
                    <div class="layui-container">
                        <div class="pear-row">
                            <div class="pear-col-xs24">
                                <div class="layui-card">
                                    <div class="layui-card-header exam-header">
                                        {{-d.type_str}}
                                    </div>
                                    <div class="layui-card-content exam-title">
                                        {{-d.topic_str}}
                                    </div>
                                </div>
                                <div class="layui-card">
                                {{ if(d.cate ==2 ){ }}
                                <div class="pear-row layui-col-space5 exam-form">
                                    {{ d.item.forEach(function(item){ }}
                                    <div class=" pear-col pear-col-xs24 pear-col-md12">
                                        <input type="radio" name="radio" value="{{=item.code}}" lay-skin="none">
                                        <div lay-radio class="lay-skin-checkcard">
                                            <div class="lay-skin-checkcard-avatar">
                                                <div>{{=item.code}}</div>
                                            </div>
                                            <div class="lay-skin-checkcard-detail">
                                            {{=item.item}}
                                            </div>
                                        </div>
                                    </div>
                                    {{ }) }}
                                </div>
                                {{ } if(d.cate == 3){ }}
                                <div class="pear-row layui-col-space5  exam-form">
                                    {{ d.item.forEach(function(item){ }}
                                    <div class=" pear-col pear-col-xs24 pear-col-md12">
                                        <input type="checkbox" name="checkbox[]" value="{{=item.code}}" lay-skin="none">
                                        <div lay-checkbox class="lay-skin-checkcard">
                                            <div class="lay-skin-checkcard-avatar">
                                                <div>{{=item.code}}</div>
                                            </div>
                                            <div class="lay-skin-checkcard-detail">
                                            {{=item.item}}
                                            </div>
                                        </div>
                                    </div>
                                    {{ }) }}
                                </div>
                                {{ } if(d.cate == 4){ }}
                                  <textarea name="textarea" placeholder="请解答" class="layui-textarea"></textarea>
                                {{ } if(d.cate == 5){ }}
                                  <blockquote class="layui-elem-quote">
                                    请在纸上作答,并拍照上传作答过程
                                  </blockquote>
                                  <div class="layui-upload-drag" style="display: block; width:200px;height:200px;color:#666;overflow:hidden;text-align:enter;" id="ID-upload-demo-drag">
                                        <i class="layui-icon layui-icon-camera"></i> 
                                        <div>拍照上传</div>
                                        <input type="hidden" name="image" value="">
                                  </div>
                                {{ } }}
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
                <div class="layui-container layui-hide" id="answer">
                    <div class="pear-row">
                        <div class="pear-col-xs24">
                            {{ if( d.cate ==4 || d.cate == 5 ){ }}
                              <div class="answer-result">
                                <div class="answer-result-right">
                                  正确
                                </div>
                                <div class="answer-result-warning">
                                  错误
                                </div>
                              </div>
                            {{ } }}  
                            <hr class="layui-border-blue">
                            <div class="layui-card">
                            <div class="tips">
                                <div class="info layui-bg-blue">
                                    
                                </div>
                            </div>
                            <div id="teacher"></div>
                            <div class="layui-card">
                                <div class="layui-elem-quote">正确答案: 
                                {{ if(d.cate == 1){ }}
                                    {{ d.item.forEach(function(item){ }}
                                        <span class="layui-bg-blue">{{=item.item}}</span>
                                   {{ }) }}
                                {{ }else{ }}
                                    <span class="layui-bg-blue">{{=d.answer}}</span>
                                {{ } }}
                                </div>
                                <div class="layui-elem-quote">分析与解答</div>
                                <div class="layui-card">
                                {{=d.explain}}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `,{
                tagStyle: 'modern', // 采用新版本的标签风格
                cache:false, // 不缓存模板
              });
            templateInst.render(data, function (html) {
                $(dom).html(html);
                form.render();
                upload.render({
                    elem: '#ID-upload-demo-drag',
                    url: '/ajax/upload',
                    size:1024000,
                    done: function(res){
                      if(res.code == 1){
                        layer.msg('上传成功');
                        $('#ID-upload-demo-drag').html('<img src="'+res.data+'" style="width:200px"><input type="hidden" name="image" value="'+res.data+'">');
                      }
                    }
                  });
                form.on('submit(submitSave)',function(result){
                    console.log(result);
                    if(data.cate == 1) {
                        if(JSON.stringify(result.field) == '{}'){
                            layer.msg('请填写答案');
                            return false;
                        }
                        let answer = new Array();
                        $('input[name="text[]"]').each(function(){
                            answer.push($(this).val());
                        })
                        console.log(answer);
                        $.each(data.item,function(key,item){
                            if(item.code.includes(answer[key]) == false){
                                data.result =1;
                            }
                        })
                        data.fruit = answer;
                        //data.result = result.field.checkbox == data.answer?2:1;
                        
                    }
                    if(data.cate == 2) { 
                        if(result.field.radio == undefined){
                            layer.msg('请选择答案');
                            return false;
                        }
                        data.fruit = result.field.radio;
                        data.result = result.field.radio == data.answer?2:1;
                    }
                    if(data.cate == 3) {
                        if(JSON.stringify(result.field) == '{}'){
                            layer.msg('请选择答案');
                            return false;
                        }
                        let fruit = "";
                        $('input[name="checkbox[]"]:checked').each(function(){
                            fruit += $(this).val();
                        })
                        data.fruit = fruit;
                        data.result = fruit== data.answer?2:1;
                        console.log(data);
                        
                    }
                    if(data.cate == 4) {
                        if(result.field.textarea == ''){
                            layer.msg('请输入答案');
                            return false;
                        }
                        data.fruit = result.field.textarea;
                        _this.initverify(data);
                        return false;
                    }
                    if(data.cate == 5) {
                    	if(result.field.image == ''){
                            layer.msg('请上传答案图片');
                            return false;
                        }
                        data.fruit = result.field.image;
                        _this.initverify(data);
                        return false;
                    }
                    postData(_this.options.url,data).then(function (result){
                        console.log(result);
                    	if(result.code == 1){
                    		_this.options.data = result.data;
                    	}else{
                            console.log(result);
                            /**弹出正确率及下一步操作 */
                            _this.initWorker(result.data);
                            layer.close(_this.options.targetlayer);
                            return false;
                        }
                        
                    });
                    
                    if(data.result == 1){
                        $('.tips>.info').html('<img src="/static/l.jpg"><span>答错了,看看解析也许有用</span><i class="layui-icon layui-icon-next"></i>')
                        $('#answer').removeClass('layui-hide');
                        if(data.cate == 1) {
                            $('.exam-title .layui-inline').addClass('lay-skin-warning');
                        }
                        if(data.cate == 2) {
                            $('.layui-form-radio.layui-form-radioed[lay-skin="none"]>.lay-skin-checkcard').addClass('lay-skin-warning');
                        }
                        if(data.cate == 3) {
                            $(' .layui-form-checkbox.layui-form-checked[lay-skin="none"]>.lay-skin-checkcard').addClass('lay-skin-warning');
                        }
                        if(data.cate == 4) {}
                        if(data.cate == 5) {}
                    }
                    if(data.result == 2){
                        $('.tips>.info').html('<img src="/static/h.jpg"><span>答对了,看看解析巩固一下</span><i class="layui-icon layui-icon-next"></i>')
                        $('#answer').removeClass('layui-hide');
                        if(data.cate == 1) {
                            $('.exam-title .layui-inline').addClass('lay-skin-right');
                        }
                        if(data.cate == 2) {
                            $('.layui-form-radio.layui-form-radioed[lay-skin="none"]>.lay-skin-checkcard').addClass('lay-skin-right');
                        }
                        if(data.cate == 3) {
                            $(' .layui-form-checkbox.layui-form-checked[lay-skin="none"]>.lay-skin-checkcard').addClass('lay-skin-right');
                        }
                        if(data.cate == 4) {}
                        if(data.cate == 5) {}
                    }
                    $('.common-menu >.menu').toggleClass('layui-hide');
                    return false;
                })
                $(document).on('click','.common-menu > .menu2',function(){
                   console.log(_this.options.data);
                    _this.tplrender(_this.options.data,$('#targetExam'));
                    return false;
                })
            });
        }
        /**
         * 目标考试
         * @param {*} data 
         */
        this.initExam = function(option){
            this.options = $.extend(this.options,option);
            let _this = this;
            layer.open({
                type: 1,
                title: false, // 禁用标题栏
                closeBtn: false, // 禁用默认关闭按钮
                area: ['100%', '100%'],
                scrollbar: false, // 暂时屏蔽浏览器滚动条
                anim: -1, // 禁用弹出动画
                isOutAnim: true, // 禁用关闭动画
                resize: false,  // 禁用右下角拉伸尺寸
                id: 'exam-target-layer-view',
                skin: 'exam-target-layer-view', // className
                content: ['<div class="layui-layout" id="targetExam">','</div>'].join(''),
                success: function(layero, index, that){
                    _this.options.targetlayer = index;
                    if(_this.options.data == null){
                        postData(_this.options.url).done(function (result){
                            _this.options.data = result.data;
                            _this.tplrender(result.data,$('#targetExam'))
                        })
                    }
                }
            })
        }
        function postData(url,data = '') {
            var defer = $.Deferred();
            var symbol = url.indexOf('?') !== -1 ? '&' : '?';
            $.post(url, data,function (result) {
                defer.resolve(result)
            }, "json");
            return defer.promise();
        }
        function getData(url,data=''){
            var defer = $.Deferred();
            var symbol = url.indexOf('?') !== -1 ? '&' : '?';
            $.get(url,function (result) {
                defer.resolve(result)
            }, "json");
            return defer.promise();
        }
        var tplverify = function (data,dom){
            var templateverify = laytpl(`
                    <div class="layui-container">
                        <div class="pear-row">
                            <div class="pear-col-xs12 pear-col-md8">
                                <div class="layui-card">
                                    <div class="layui-card-header exam-header">
                                        {{-d.type_str}}
                                    </div>
                                </div>
                                <div class="layui-card" style="min-height:300px;background-color: rgba(122, 154, 243, 0.1);">
                                    <div class="verify-info">
                                     <i class="layui-icon layui-icon-time"></i>
                                     <div class="title">提交成功!等待批改</div>
                                     <div class="descript">答案已提交 等待老师批改反馈</div>
                                    </div>
                                </div>
                            </div>
                            <div class="pear-col-xs12 pear-col-md16">
                                <div class="layui-card" style="min-height:300px; border:3px solid #1e9fff" id="worker">
                                  
                                </div>
                            </div>
                        </div>
                    </div>`,
                {
                    tagStyle: 'modern', // 采用新版本的标签风格
                    cache:false, // 不缓存模板
                });
                templateverify.render(data, function (html) {
                    $(dom).html(html);
                })
        }
        this.initverify = function (data){
            layer.open({
                type: 1,
                title: false, // 禁用标题栏
                closeBtn: false, // 禁用默认关闭按钮
                area: ['100%', '100%'],
                scrollbar: false, // 暂时屏蔽浏览器滚动条
                anim: -1, // 禁用弹出动画
                isOutAnim: true, // 禁用关闭动画
                resize: false,  // 禁用右下角拉伸尺寸
                id: 'exam-verify-layer-view',
                skin: 'exam-verify-layer-view', // className
                content: ['<div class="layui-layout" id="verifyExam">','</div>'].join(''),
                success: function(layero, index, that){
                    console.log(_this.options);
                    _this.options.varifylayer = index;
                    postData('/index/index/worker',data).done(function (result){
                           tplverify(data,$('#verifyExam'));
                           _this.eventVerify(result.data); 
                    })
                }
            })
        }
        this.eventVerify = function(id){
            getData('index/index/worker?id='+id).done(function(rlt){
                if(rlt.code == 1){
                    clearTimeout(timerId); 
                    layer.msg('已批改');
                    const data = rlt.data;
                    postData(_this.options.url,data).then(function (result){
                        console.log(result);
                    	if(result.code == 1){
                    		_this.options.data = result.data;
                    	}else{
                            console.log(result);
                            /**弹出正确率及下一步操作 */
                            _this.initWorker(result.data);
                            layer.close(_this.options.targetlayer);
                            return false;
                        }
                    });
                    if(data.result == 1){
                        $('.tips>.info').html('<img src="/static/l.jpg"><span>答错了,看看解析也许有用</span><i class="layui-icon layui-icon-next"></i>')
                        $('.answer-result-warning').addClass('layui-skin-warning');
                        let answerTpl =  '<div class="layui-elem-quote">答案：</div><div class="answer-result"><div class="answer-result-warning layui-skin-warning">错误</div></div>"';
                        $('#answer').removeClass('layui-hide');
                    }
                    if(data.result == 2){
                        $('.tips>.info').html('<img src="/static/h.jpg"><span>答对了,看看解析巩固一下</span><i class="layui-icon layui-icon-next"></i>')
                        $('.answer-result-right').addClass('layui-skin-right');
                        let answerTpl = '<div class="layui-elem-quote">答案：</div><div class="answer-result"><div class="answer-result-right layui-skin-right">正确</div></div>"';
                        $('#answer').removeClass('layui-hide');
                    }
                    $('.common-menu >.menu').toggleClass('layui-hide');
                    /***答题区 等待区 加老师批注 */
                    let teacherTpl =  '<div class="layui-elem-quote">老师批解</div>';
                    let ImageTpl = '';
                    if(data.image != ''){
                        ImageTpl = '<div class="layui-card"><img src="'+data.image+'" width="360px"></div>';
                    }
                    let vedioTpl = '';
                    if(data.video != ''){
                        vedioTpl = '<div class="layui-card"><video src="'+data.video+'" width="360px"></video></div>';
                    }
                    let backTpl='<button class="pear-btn pear-btn-success" id="backBtn">确认返回</button>'
                    $('#teacher').html(teacherTpl+ImageTpl+vedioTpl);
                    $('#worker').html( answerTpl + teacherTpl+ImageTpl+vedioTpl);
                    $(document).on('click','#backBtn',function(){
                        layer.close(_this.options.varifylayer);
                    })
                }else{
                    clearTimeout(timerId);  
                    let timerId = setTimeout(function(){
                        _this.eventVerify(id);
                    },5000)
                }
            })
        }
        this.initWorker = function(data){
        	layer.open({
                type: 1,
                title: false, // 禁用标题栏
                closeBtn: false, // 禁用默认关闭按钮
                area: ['100%', '100%'],
                scrollbar: false, // 暂时屏蔽浏览器滚动条
                anim: -1, // 禁用弹出动画
                isOutAnim: true, // 禁用关闭动画
                resize: false,  // 禁用右下角拉伸尺寸
                id: 'exam-worker-layer-view',
                skin: 'exam-worker-layer-view', // className
                content: ['<div class="layui-layout" id="workerExam">','</div>'].join(''),
                success: function(layero, index, that){
                    const kid = _this.options.data.knowledge_id;
                    /*************/
                    workerTpl(data,'#workerExam');
                    $(document).on('click','.btn-video',function(){
                        layer.closeAll();
                    })
                    $(document).on('click','.btn-back',function(){
                        window.location.href = "/index/index/index";
                    })
                    $(documnet).on('click','.btn-survey',function(){
                        
                        _this.initExam({
                            data:null,
                            url:'/index/index/variants?id='+kid,
                            type:'variants',
                            targetlayer:null,
                            varifylayer:null,
                            workerlayer:null
                        });
                        layer.close(index);
                    })

                }
            })
        }
        var workerTpl = function(data,dom){
            var templateworker = laytpl(`
                <div class="layui-container">
                    <div class="pear-row">
                        <div class="pear-col-xs24">
                            <div class="layui-card" style="border:1px solid #000;border-radius:5px;">
                                <div class="layui-card-header" style="font-size:20px;font-weight:bold;">
                                    {{ if(d.pass == 1){ }}
                                    <i class="layui-icon layui-icon-face-smile" style="font-size:28px;color:#3aa84b"></i><span style="margin-left:10px;">恭喜，已掌握</span>
                                    {{ } }}
                                    {{ if(d.pass == 0){ }}
                                    <i class="layui-icon layui-icon-face-cry" style="font-size:28px;color:#f5535c"></i><span style="margin-left:10px;">很遗憾，未通过</span>
                                    {{ }}}
                                </div>
                            </div>
                            <div class="layui-card">
                                <div class="layui-elem-quote" style="font-size:18px;">
                                    正确率:{{=d.rate}}% <span style="color:#999;font-size:14px;margin-left:15px;">可在完成所有环节后统一查看答题记录</span>
                                </div>
                                <div class="layui-elem-quote" style="border-color:#eee;">
                                    {{ d.result.forEach(function(index,item){ }}
                                        {{ if(item.result == 2){ }}
                                            <div class="layui-bg-green" style="width:20px;height:20px;border-radius:50%;display:inline-block;margin-right:10px;">{{=index+1}}</div>
                                        {{ }else{ }}
                                            <div class="layui-bg-red" style="width:20px;height:20px;border-radius:50%;display:inline-block;margin-right:10px;">{{=index+1}}</div>
                                        {{ }}}
                                    {{ }) }}
                                </div>
                            </div>
                            {{ if(d.type == 'target'){ }}
                            <div class="layui-card" style="font-size:18px;font-weight:400">
                                {{ if(d.pass == 0){ }}
                                    <span style="color:#000">复习建议:</span><span style="color:#454545"> 未通过检测 证明没有掌握基础概念，需要通过微课视频巩固基础</span>
                                {{ }else{ }}
                                    <span style="color:#000">复习建议:</span><span style="color:#454545"> 你已经掌握知识基础概念，下面挑战几道更难的变式题来拓展提高吧</span>
                                {{ } }}
                            
                            </div>
                            <div class="layui-card"  style="border:1px solid #000;border-radius:5px; font-size:18px;font-weight:400">
                                {{ if(d.pass == 0){ }}
                                    <i class="layui-icon layui-icon-video" style="font-size:28px;color:#1e9fff"></i> <span style="margin-left:10px; margin-right:10px;">学习微课视频</span> <button class="pear-btn pear-btn-primary btn-video">下一步</button>
                                {{ }else{ }}
                                    <i class="layui-icon layui-icon-survey" style="font-size:28px;color:#1e9fff"></i> <span style="margin-left:10px; margin-right:10px;">完成变式题</span> <button class="pear-btn pear-btn-primary btn-survey">下一步</button>
                                {{ } }}
                            
                            </div>
                            {{ } else { }}
                            <div class="layui-card"  style="border:1px solid #000;border-radius:5px; font-size:18px;font-weight:400">
                                {{ if(d.pass == 0){ }}
                                    <div class="layui-col-xs12">
                                        <button class="pear-btn pear-btn-primary btn-video">重新学习微课</button>
                                    </div>
                                    <div class="layui-col-xs12">
                                        <button class="pear-btn pear-btn-primary btn-back">返回知识列表</button>
                                    </div>
                                {{ }else{ }}
                                    <button class="pear-btn pear-btn-primary btn-back">返回知识列表</button>
                                {{ } }}
                            </div>
                            {{ } }}
                        </div>
                        
                    </div>
                </div>`,
            {
                tagStyle: 'modern', // 采用新版本的标签风格
                cache:false, // 不缓存模板
            });
            templateworker.render(data, function (html) {
                $(dom).html(html);
            })
        }
    }
    exports(MOD_NAME, exam);
});